package com.android.dx.youzan.utils;

import android.os.Environment;

import com.blankj.utilcode.util.EncryptUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Author: Ligang
 * Date: 2020/01/11
 * Description:
 */
public class FileDownloadUtils {
    private static final String fileRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
            + "youzan";

    static {
        File file = new File(fileRoot);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static File[] download(String bigUrl, String originUrl) {
        File f1 = download(bigUrl);
        File f2 = download(originUrl);
        if (f1 == null || f2 == null) {
            return null;
        }
        return new File[]{f1, f2};
    }

    private static File download(String url) {
        File file = new File(fileRoot, buildFileName(url));
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            fos = new FileOutputStream(file);
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            inputStream = conn.getInputStream();
            byte[] buff = new byte[1024 * 40];
            int len;
            while ((len = inputStream.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private static String buildFileName(String url) {
        return EncryptUtils.encryptMD5ToString(url) + ".png";
    }
}
